package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: wzw
 * @CreateTime: 2025-10-05  13:41
 * @Description: TODO
 **/
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理支付超时订单
     */
    @Scheduled(cron = "10 * * * * ?")//每隔10分钟执行一次
//    @Scheduled(cron = "0/5 * * * * ?")//测试 每隔5s 执行一次
    public void processTimeoutOrders(){
        log.info("{} 定时任务OrderTask执行：处理支付超时订单",LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT,time);
        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orderMapper.update(Orders.builder()
                        .id(orders.getId())
                        .status(Orders.CANCELLED)
                        .cancelReason("支付超时，取消订单")
                        .cancelTime(LocalDateTime.now())
                        .build());
            }
        }
    }
    /*
     * @description: 处理派送订单的状态为已完成
     * @author: wzw
     * @date: 2025/10/5 0005 13:48
     * @param:
     * @return:
     **/
    @Scheduled(cron = "0 0 1 * * ?") //每天凌晨1点执行一次
//    @Scheduled(cron = "0/5 * * * * ?")//测试 每隔5s 执行一次
    public void processDeliveryOrders(){
        log.info("{} 定时任务OrderTask执行：处理一直处于“派送中”状态订单的状态为已完成",LocalDateTime.now());

        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS,LocalDateTime.now().plusMinutes(-60));
         if (ordersList != null && ordersList.size() > 0){
             for (Orders orders : ordersList) {
                 orderMapper.update(Orders.builder()
                         .id(orders.getId())
                         .status(Orders.COMPLETED)
                         .build());
             }
         }
    }


}
